//
//  TLDetailViewContentViewController.m
//  Growth
//
//  Created by MEET on 12-1-13.
//  Copyright 2012 MEETStudio. All rights reserved.
//

#import "TLDetailViewContentViewController.h"
#import "CommentViewController.h"

#import "SDImageView+SDWebCache.h"


#import "Config.h"
#import "PersonalViewController.h"

#import "DiaryPhotoBrowseViewController.h"

static WebConnectionArray *diaryComment_connection;
static WebConnectionArray *diaryLike_connection;
static WebConnection *diaryContent_connection;

static ASIHTTPConnection *getThread_connect;
static ASIHTTPConnection *sendComment_connect;

static  BOOL isAddNewComment  = false;


@implementation TLDetailViewContentViewController

@synthesize delegate;

@synthesize userId;

@synthesize type;

@synthesize userIcon;
@synthesize userName;

@synthesize localLabel; 

//data
@synthesize diaryDict;

@synthesize scrollView;
@synthesize commentView;

//add comment
@synthesize commentText;
@synthesize commentCountLabel;
@synthesize superId;
@synthesize commentTo;
@synthesize commentViewController;

//favor
@synthesize favorCountLabel;

- (id)initWithPost:(NSDictionary *)dict{

	[super init];
	
	self.diaryDict = dict;
	
    pageNo = 1;
        
    diaryId = [[dict objectForKey:@"ThreadID"] intValue];
       
    
    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillHide:) 
													 name:UIKeyboardWillHideNotification 
												   object:nil];		
	}
 
     
	return self;
}


- (id)initWithDid:(int)did conttentType:(NSString *)conttentType{
    
    [super init];
    
    self.type = conttentType;
    diaryId = did;
    
    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillHide:) 
													 name:UIKeyboardWillHideNotification 
												   object:nil];		
	}
    
    
	return self;

    
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
     self.userId=[[[NSUserDefaults standardUserDefaults] valueForKey: USER_ID] intValue];
  
     [self.scrollView setFrame:CGRectMake(0, 0, 320, self.view.frame.size.height -50)];
    
       
       self.view.backgroundColor = [UIColor clearColor];

 
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"转发" style:UIBarButtonSystemItemDone target:self action:@selector(forwardMicroBlog)];
    
    
    
   
    GrowthAppDelegate *appDelegate =
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];

    [self.navigationItem setRightBarButtonItem:rightButton];
    [rightButton release];
    

    
    
    [self loadDetailDiary];
    
    [self initContentView];
    
    [self initGrowingTextView];

    
    [super viewDidLoad];

    
}

- (void)forwardMicroBlog{

    
    RecordViewController *ViewController =   [[RecordViewController alloc] initWithThreadID:diaryId];
    
    GrowthAppDelegate *appDelegate =
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    [self.navigationController pushViewController:ViewController animated:YES];
    [ViewController release];
    

    
}

#pragma mark initContentView

-(NSString *)changeStringFommat:(NSString *)str{
    
    PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];   
    
    return  [methodEngine changeStringFommat:str];
 
    
}



-(void)initContentView{
    
   
    //初始化多级评论参数
    self.superId = -1;
    self.commentTo = -1;
    
    
    localLabel.textColor = Text_Color;
    
     
//        if(![[self.diaryDict objectForKey:@"timelineAttachmentId"] isMemberOfClass:[NSNull class]]){
//            CGRect frame;
//            frame.size.width=50; frame.size.height=50;
//            frame.origin.x=0; frame.origin.y=0;
//            UIImageView* asyncImage = [[UIImageView alloc]
//                                       initWithFrame:frame];
//            asyncImage.tag = 999;
//            
//            NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",BASEURL,@"/commons/attachment/download",[self.diaryDict objectForKey:@"timelineAttachmentId"]];
//            NSURL *url = [NSURL URLWithString:string];	
//            
//            [asyncImage setClipsToBounds:YES];
//            asyncImage.layer.cornerRadius = 25;
//            //[asyncImage setImageWithURL:url ];
//              [asyncImage setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon]; 
//            
//            [userIcon addSubview:asyncImage];
//            
//            if (![[self.diaryDict objectForKey:@"userId"] isMemberOfClass:[NSNull class]]) {
//                
//                userIcon.tag = [[self.diaryDict objectForKey:@"timelineId"] intValue];
//                [userIcon addTarget:self action:@selector(toBabyTimelineView:) forControlEvents:UIControlEventTouchUpInside];
//                
//            }
//            
//        }
    
    
    
        
    //发表时间
    
    NSDate *zoneDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
    NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:interval];
    
    
    NSTimeInterval _interval = [date timeIntervalSince1970];
    long long int longIntTime = (long long int)_interval*1000; 
      
    long long int creatTime;
    
    if (![[self.diaryDict objectForKey:@"DateCreated"] isMemberOfClass:[NSNull class]]) {
        
        
        creatTime = [[self.diaryDict objectForKey:@"DateCreated"] longLongValue] +interval *1000;
       
        long long int detaTiem = (longIntTime-creatTime)/1000; //几秒前
        
        
        NSDate *diaryDate = [NSDate dateWithTimeIntervalSince1970:creatTime/1000];
        CLog(@"cur date %@, diary date %@ ",date, diaryDate );
        
        if (detaTiem <0) {
            NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTime/1000];
            
            NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
            int create_year = [[createDateStr substringWithRange: NSMakeRange(0, 4)] intValue];
            int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
            int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
            int hour = [[createDateStr substringWithRange:NSMakeRange(11, 2)] intValue];
            int min = [[createDateStr substringWithRange:NSMakeRange(14, 2)] intValue];
            NSString *dayString = [NSString stringWithFormat:@"%d日",create_day];
            NSString *monthString = [NSString stringWithFormat:@"%d月",create_month];

            NSString *titleStr = [NSString stringWithFormat:@"%@%@ %02d:%02d",monthString,dayString,hour, min];
           
            self.navigationItem.title = titleStr;
        }
        
        if(detaTiem >=0 && detaTiem<60){
         
            
           // if (detaTiem < 10) {
                             
                self.navigationItem.title = @"刚刚";
                
           // }
            
        }

    
        if(detaTiem>59&&detaTiem<3600){
            
            detaTiem = detaTiem/60; //几分钟前
            
            self.navigationItem.title = [NSString stringWithFormat:@"%lld分钟前",detaTiem];
        
        }
        
        if(detaTiem>=60*60 && detaTiem < 3600*24){
            
            detaTiem = detaTiem/3600; //几hour前
           
            self.navigationItem.title  = [NSString stringWithFormat:@"%lld小时前",detaTiem];
        }
        
        if(detaTiem>60*60*24 && detaTiem < 3600*24*2){
            
            detaTiem = detaTiem/(3600*24); //几hour前
    
            self.navigationItem.title = [NSString stringWithFormat:@"%lld天前",detaTiem];
        }
        
        if(detaTiem>=3600*24*2){
            
            NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTime/1000];
            
            NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
            int create_year = [[createDateStr substringWithRange: NSMakeRange(0, 4)] intValue];
            int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
            int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
            int hour = [[createDateStr substringWithRange:NSMakeRange(11, 2)] intValue];
            int min = [[createDateStr substringWithRange:NSMakeRange(14, 2)] intValue];
            NSString *dayString = [NSString stringWithFormat:@"%d日",create_day];
            NSString *monthString = [NSString stringWithFormat:@"%d月",create_month];
            
            NSString *titleStr = [NSString stringWithFormat:@"%@%@ %02d:%02d",monthString,dayString,hour, min];
           
            self.navigationItem.title = titleStr;
            
        }
        
       
    }
      
       
    //好友名字
    
           if(![[self.diaryDict objectForKey:@"Author"] isMemberOfClass:[NSNull class]]){
            NSString *friendName=[self.diaryDict objectForKey:@"Author"]; 
            userName.text=friendName;
            [userName setTextColor:Text_Color];
        }
   
      
    yuanJiaoView = [[UIView alloc]init];
    yuanJiaoView.tag = 105;
    yuanJiaoView.backgroundColor=[UIColor whiteColor];
    yuanJiaoView.layer.cornerRadius=3;
    
    yuanJiaoView.layer.shadowColor = [[UIColor darkGrayColor] CGColor];
    yuanJiaoView.layer.shadowOffset = CGSizeMake(0.5, 0.5);
    yuanJiaoView.layer.shadowOpacity = 0.7;
        
    
    [self.scrollView insertSubview:yuanJiaoView atIndex:1];
            
            UILabel *contentLable = [[UILabel alloc]init];
            contentLable.numberOfLines = 0;
            contentLable.lineBreakMode = UILineBreakModeWordWrap;
            [contentLable setFont:[UIFont systemFontOfSize:14]];
        
                               
                NSString *content = [self.diaryDict objectForKey:@"Body"];
              
                content = [self changeStringFommat:content];
                
                UIFont *font = [UIFont systemFontOfSize:15];
                CGSize size = [content sizeWithFont: font constrainedToSize: CGSizeMake(248.0f, 6000.0f) lineBreakMode: UILineBreakModeWordWrap];   
               
                [contentLable setFrame:CGRectMake(25, 85, 270, size.height+20)];
                contentLable.backgroundColor = [UIColor clearColor];
                contentLable.text = content;
                
                [self.scrollView addSubview:contentLable];
                
                [contentLable release];
                        
            [yuanJiaoView setFrame:CGRectMake(20, 85, 280, contentLable.frame.size.height)];
          
    
    //转发内容
    if (![[self.diaryDict objectForKey:@"GetOriginalThread"] isMemberOfClass:[NSNull class]]) {
        
        NSDictionary *subDict = [diaryDict objectForKey:@"GetOriginalThread"];
        NSString *subContent = [NSString stringWithFormat:@"%@: %@",[subDict objectForKey:@"Author"],[subDict objectForKey:@"Body"]];
        UIFont *font = [UIFont systemFontOfSize:15];
        CGSize size = CGSizeMake(265,2000);
        CGSize labelsize = [subContent sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeCharacterWrap];
        
        UILabel *subContentLable = [[UILabel alloc]initWithFrame:CGRectMake(contentLable.frame.origin.x+7 , contentLable.frame.origin.y + contentLable.frame.size.height, labelsize.width, labelsize.height +5)];
        
        subContentLable.numberOfLines = 0;
        subContentLable.lineBreakMode = UILineBreakModeCharacterWrap;
        subContentLable.textColor = [UIColor darkGrayColor];
        [subContentLable setFont:[UIFont systemFontOfSize:14]];
        
        //bg
        UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(subContentLable.frame.origin.x-5, subContentLable.frame.origin.y, labelsize.width +10, labelsize.height +30)];
        bgImageView.image = [[UIImage imageNamed:@"bian2_geren_iphone.png"] stretchableImageWithLeftCapWidth:100 topCapHeight:30];
        [self.scrollView addSubview:bgImageView];
        
        //time
        NSDate *zoneDate = [NSDate date];
        NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
        NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
        NSString *DateCreated = [subDict objectForKey:@"DateCreated"];
        NSString *dateStr = [DateCreated substringWithRange:NSMakeRange(6, 13)];
        
        creatTime = [dateStr longLongValue];
        creatTime = creatTime/1000 +interval;
        
        //日志时间
        NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTime];
        
        CLog(@"create date %@", nd);
        
        NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
        UILabel *subTimeLable = [[UILabel alloc]initWithFrame:CGRectMake(130, bgImageView.frame.size.height -25, 140, 25)];
        subTimeLable.textColor = [UIColor darkGrayColor];
        subTimeLable.font = [UIFont systemFontOfSize:12];
        subTimeLable.backgroundColor = [UIColor clearColor];
        subTimeLable.text = createDateStr;
        [bgImageView addSubview:subTimeLable];
        [subTimeLable release];
        
        
        [bgImageView release];
        
        [scrollView addSubview:subContentLable];
        subContentLable.backgroundColor = [UIColor clearColor];
        subContentLable.text = subContent;
        
        
        
        [yuanJiaoView setFrame:CGRectMake(yuanJiaoView.frame.origin.x, yuanJiaoView.frame.origin.y, yuanJiaoView.frame.size.width, yuanJiaoView.frame.size.height +40 + labelsize.height+5)];
        [self conttentViewShadow];
        
        
    }
    else{
        
        
        
        [yuanJiaoView setFrame:CGRectMake(yuanJiaoView.frame.origin.x, yuanJiaoView.frame.origin.y, yuanJiaoView.frame.size.width, contentLable.frame.size.height +40)];
        [self conttentViewShadow];
        
    }
    
    
        
        //放评论的view
        commentView.layer.cornerRadius = 2;
        commentView.backgroundColor = [UIColor whiteColor];
                
       
    [yuanJiaoView setClipsToBounds:NO];
        
     //[favorButton release];
    [self conttentViewShadow];

    UIImageView *favorImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"like_top_iphone.png"]];

    [favorImageView setFrame:CGRectMake(212, 58, 14, 12)];

    [self.scrollView addSubview:favorImageView];
    [favorImageView release];
    
        
    favorCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(227, 53, 28, 21)];

    
    [favorCountLabel setTextColor:Text_Color];
    
    
    favorCountLabel.text= [NSString stringWithFormat:@"%@",[diaryDict objectForKey:@"ReplyCount"]];
    [favorCountLabel setFont:[UIFont systemFontOfSize:12]];
    favorCountLabel.backgroundColor=[UIColor clearColor];
    [self.scrollView addSubview:favorCountLabel];
    
    UIImageView *commentImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"said_top_iphone.png"]];

    [commentImageView setFrame:CGRectMake(259, 58, 14, 12)];

    [self.scrollView addSubview:commentImageView];
    [commentImageView release];
    
    
    
    commentCountLabel=[[UILabel alloc]initWithFrame:CGRectMake(274, 56, 28, 21)];

    
    [commentCountLabel setTextAlignment:UITextAlignmentRight];
    [commentCountLabel setTextColor:Text_Color];
    commentCountLabel.text= [NSString stringWithFormat:@"%@",[diaryDict objectForKey:@"ReplyCount"]];
    [commentCountLabel setBackgroundColor:[UIColor clearColor]];
    [commentCountLabel setFont:[UIFont systemFontOfSize:12]];
    [commentCountLabel sizeToFit];
    commentCountLabel.backgroundColor=[UIColor clearColor];
    [self.scrollView addSubview:commentCountLabel];
    
    [commentCountLabel setText:[NSString stringWithFormat:@"%d",[[self.diaryDict objectForKey:@"ReplyCount"] intValue]]];
    
    [favorCountLabel setText:[NSString stringWithFormat:@"%d",[[self.diaryDict objectForKey:@"ReplyCount"] intValue]]];

          
    [scrollView setContentSize:CGSizeMake(320, yuanJiaoView.frame.size.height +200)];
      
    commentView.layer.cornerRadius = 2;
    commentView.layer.shadowColor = [[UIColor blackColor] CGColor];
    commentView.layer.shadowOffset = CGSizeMake(0, 1);
    CGRect rect = commentView.frame;
    rect.origin.y = yuanJiaoView.frame.origin.x + yuanJiaoView.frame.size.height + 40;
    commentView.frame = rect;

}


#pragma mark 显示本地记录
- (void)initLocalContentView{
	CLog(@"Locale content dict %@", diaryDict);    
    
    localLabel.textColor = Text_Color;
    userName.textColor = Text_Color;
    
    [self.scrollView setFrame:CGRectMake(0, 0, 320, self.contentView.frame.size.height -50)];
    
    
    NSDictionary *dict ;
    
    NSString *JsonString = [self.diaryDict objectForKey:@"json"];
    if (JsonString != nil) {
        NSError *error = nil;
        NSData *dat=[JsonString dataUsingEncoding: NSUTF8StringEncoding];
        dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:dat error:&error];
    }

           
    
    //名字
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userName"]) {
        
        userName.text =  [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    }
    
    
	//头像
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userAttachmentId"]) {
        
        
        CGRect frame;
        frame.size.width=50; frame.size.height=50;
        frame.origin.x=0; frame.origin.y=0;
        UIImageView* asyncImage = [[UIImageView alloc]
                                   initWithFrame:frame];
        asyncImage.tag = 999;
        
       // NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",BASEURL,@"/commons/attachment/download",[self.diaryDict objectForKey:@"createdAttachment"]];
        
         NSString *string=[NSString stringWithFormat:@"%@/%@/%@/100x100",UCENTERBASEURL,@"gravatar",[self.diaryDict objectForKey:@"createdAttachment"]];
        
        NSURL *url = [NSURL URLWithString:string];	
        
        [asyncImage setClipsToBounds:YES];
        asyncImage.layer.cornerRadius = 3;
        //[asyncImage setImageWithURL:url ];
        [asyncImage setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon];         
        [userIcon addSubview:asyncImage];
        
        
        
        if([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]){
            userIcon.tag = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
            [userIcon addTarget:self action:@selector(toUserView:) forControlEvents:UIControlEventTouchUpInside];   
        }
        
	}
    

    
    
     
    //发表时间
    
    NSDate *zoneDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
    NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:interval];
    
    NSTimeInterval time = [date timeIntervalSince1970];
    long long int longIntTime = (long long int)time*1000; 
    // long long int creatTime = [[self.diaryDict objectForKey:@"diaryDate"] longLongValue];
    
    long long int creatTime;
    if ([dict objectForKey:@"createdDate"] != nil) {
        creatTime = [[dict objectForKey:@"createdDate"] longLongValue] +interval *1000;
        
        
        long long int detaTiem = (longIntTime-creatTime )/1000; //几秒前
        if (detaTiem <0) {
            NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTime/1000];
            
            NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
            int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
            int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
            int hour = [[createDateStr substringWithRange:NSMakeRange(11, 2)] intValue];
            int min = [[createDateStr substringWithRange:NSMakeRange(14, 2)] intValue];
            NSString *dayString = [NSString stringWithFormat:@"%d日",create_day];
            NSString *monthString = [NSString stringWithFormat:@"%d月",create_month];

            
            NSString *titleStr = [NSString stringWithFormat:@"%@%@ %02d:%02d",monthString,dayString,hour, min];
          
            self.navigationItem.title = titleStr;
        }
        if(detaTiem>=0 &&  detaTiem<60){
         
            
          //  if (detaTiem < 10) {
               
                // [self.delegate setTimeTitle:@"刚刚"];
                
                self.navigationItem.title = @"刚刚";
                
            //}
            
        }
        
        if(detaTiem>59&&detaTiem<3600){
            
            detaTiem = detaTiem/60; //几分钟前
           
            self.navigationItem.title = [NSString stringWithFormat:@"%lld分钟前",detaTiem];
            
        }
        
        if(detaTiem>=60*60 && detaTiem < 3600*24){
            
            detaTiem = detaTiem/3600; //几hour前
           
            self.navigationItem.title  = [NSString stringWithFormat:@"%lld小时前",detaTiem];
        }
        
        if(detaTiem>60*60*24 && detaTiem < 3600*24*2){
            
            detaTiem = detaTiem/(3600*24); //几hour前
           
            
            self.navigationItem.title = [NSString stringWithFormat:@"%lld天前",detaTiem];
        }
        
        if(detaTiem>=3600*24*2){
            
            NSDate *nd = [NSDate dateWithTimeIntervalSince1970:creatTime/1000];
            
            NSString *createDateStr = [[PublicMethodEngine sharedPublicMethodEngine] NSDateToNSTring:nd];
            int create_month=[[createDateStr substringWithRange: NSMakeRange(5, 2)] intValue];
            int create_day=[[createDateStr substringWithRange: NSMakeRange(8, 2)] intValue];
            int hour = [[createDateStr substringWithRange:NSMakeRange(11, 2)] intValue];
            int min = [[createDateStr substringWithRange:NSMakeRange(14, 2)] intValue];
            NSString *dayString = [NSString stringWithFormat:@"%d日",create_day];
            NSString *monthString = [NSString stringWithFormat:@"%d月",create_month];
            
            NSString *titleStr = [NSString stringWithFormat:@"%@%@ %02d:%02d",monthString,dayString,hour, min];
            self.navigationItem.title = titleStr;
            
        }
        
               
    }
      
    
       //大圆角view
    
    
    
    yuanJiaoView = [[UIView alloc]init];
    yuanJiaoView.tag = 105;
    yuanJiaoView.backgroundColor=[UIColor whiteColor];
    yuanJiaoView.layer.cornerRadius=3;
    
    yuanJiaoView.layer.shadowColor = [[UIColor darkGrayColor] CGColor];
    yuanJiaoView.layer.shadowOffset = CGSizeMake(0.5, 0.5);
    yuanJiaoView.layer.shadowOpacity = 0.7;
    
    
    [self.scrollView insertSubview:yuanJiaoView atIndex:1];
    
    
    
    UIImageView *commentAndLikeImageView=[[UIImageView alloc] init];
    
    
      
    //文字记录
         
        if([dict objectForKey:@"fileData"] != nil){ //有图
            
            float hight = 0;
           
            
            //单张照片显示
            
            
            
                CGRect frame;
                frame.size.width=270; frame.size.height=0;
                frame.origin.x=0; frame.origin.y=1;
                UIImageView* bigPicture = [[UIImageView alloc]
                                           initWithFrame:frame];
                bigPicture.tag = 102;
                
                [bigPicture setContentMode:UIViewContentModeScaleAspectFill];
                [bigPicture setClipsToBounds:YES];
                
            NSString *imageUrlKey = [NSString stringWithFormat:@"%@",[self.diaryDict objectForKey:@"time"]]  ;
            NSData *imageData =   [[SDDataCache sharedDataCache:kImageCache_Locale_Record] dataFromKey:imageUrlKey];
            if (imageData) {
                bigPicture.image = [UIImage imageWithData:imageData];
            }
            else{//图片已经被删除
                
                 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bg_imageView" ofType:@"png"];
                bigPicture.image = [UIImage imageWithContentsOfFile:filePath];
                
            }

                
                float h;
                
                if (bigPicture.image) {
                    
                    h = (240*bigPicture.image.size.height)/bigPicture.image.size.width;
                }
                
                else{
                    h = 0;
                }
                
                [bigPicture setFrame:CGRectMake(0, 0, 270, h)];
                
                bigPicture.userInteractionEnabled = YES;
                
                //放大全屏
            if (pictureList == nil) {
                
                pictureList = [[NSArray alloc]initWithObjects:imageUrlKey, nil];
                
            }
                UIButton *fullScreenButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, bigPicture.frame.size.width, bigPicture.frame.size.height)];
                fullScreenButton.backgroundColor = [UIColor clearColor];
                [fullScreenButton addTarget:self action:@selector(toLocalFullSize:) forControlEvents:UIControlEventTouchUpInside];
                [bigPicture addSubview:fullScreenButton];
                [fullScreenButton release];
                
                //照片背景
                UIImageView *pictureBackGround=[[UIImageView alloc]initWithFrame:CGRectMake(25, 95+hight, 270, h)];
                
                pictureBackGround.userInteractionEnabled = YES;
                
                pictureBackGround.tag = 103;
                [self.scrollView addSubview:pictureBackGround];   
                
                             
                [pictureBackGround addSubview:bigPicture];
                [pictureBackGround release];
                [bigPicture release];
                hight += (h+5);
                
        
            
            UILabel *contentLabel = [[UILabel alloc]init];
            contentLabel.tag = 104;
            contentLabel.backgroundColor = [UIColor clearColor];
            contentLabel.numberOfLines = 0;
            contentLabel.lineBreakMode = UILineBreakModeWordWrap;
            [contentLabel setFont:[UIFont systemFontOfSize:14]];
            
            NSString *content = [dict objectForKey:@"diaryContent"];
            
            content = [self changeStringFommat:content];
            
            UIFont *font = [UIFont systemFontOfSize:15];
            CGSize size = [content sizeWithFont: font constrainedToSize: CGSizeMake(248.0f, 6000.0f) lineBreakMode: UILineBreakModeWordWrap];   
            
                      
            [contentLabel setFrame:CGRectMake(25, 95+hight, 270, size.height+20)];
            contentLabel.backgroundColor = [UIColor clearColor];
            contentLabel.text = content;
            
            [self.scrollView addSubview:contentLabel];
            [contentLabel release];
            
            //喜欢与评论
            
            if (![content isEqualToString:@"null"] && ![content isEqualToString:@""])  {
                
                 [yuanJiaoView setFrame:CGRectMake(20, 85, 280, hight+10+contentLabel.frame.size.height)];
                
            }
            else{
                
                 [yuanJiaoView setFrame:CGRectMake(20, 85, 280, hight+contentLabel.frame.size.height)];
            }
           
                        
            //地理位置
            
            if(![[dict objectForKey:@"local"] isMemberOfClass:[NSNull class]])
            { 
                
                localLabel.text=[dict objectForKey:@"local"];
                localLabel.hidden = NO;
                
                
                
            }
            
            
            
            //评论和喜欢
            
            [commentAndLikeImageView setFrame:CGRectMake(0, yuanJiaoView.frame.size.height-39, 258, 40)];
            [yuanJiaoView addSubview:commentAndLikeImageView];
            
            
            
        }
        
        else{
            
            UILabel *contentLable = [[UILabel alloc]init];
            contentLable.numberOfLines = 0;
            contentLable.lineBreakMode = UILineBreakModeWordWrap;
            [contentLable setFont:[UIFont systemFontOfSize:14]];
            
            
            NSString *content = [dict objectForKey:@"diaryContent"];
            
            content = [self changeStringFommat:content];
            
            UIFont *font = [UIFont systemFontOfSize:15];
            CGSize size = [content sizeWithFont: font constrainedToSize: CGSizeMake(248.0f, 6000.0f) lineBreakMode: UILineBreakModeWordWrap];   
           
            [contentLable setFrame:CGRectMake(25, 85, 270, size.height+20)];
            contentLable.backgroundColor = [UIColor clearColor];
            contentLable.text = content;
            
            [self.scrollView addSubview:contentLable];
            
            [contentLable release];
            
            [yuanJiaoView setFrame:CGRectMake(20, 85, 280, contentLable.frame.size.height)];
            
            
            
            //地理位置
            
            if(![[dict objectForKey:@"local"] isMemberOfClass:[NSNull class]])
            { 
                
                localLabel.text=[self.diaryDict objectForKey:@"local"];
                localLabel.hidden = NO;
                
                
            }
            
            
            [commentAndLikeImageView setFrame:CGRectMake(0, yuanJiaoView.frame.size.height-39, 258, 40)];
            [yuanJiaoView addSubview:commentAndLikeImageView];
            
            
            
        }
        
         
    [yuanJiaoView setClipsToBounds:NO];
    
    //[favorButton release];
    [self conttentViewShadow];
    
    UIImageView *favorImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"like_top_iphone.png"]];
    
    
    [favorImageView setFrame:CGRectMake(212, 58, 14, 12)];
    
    [self.scrollView addSubview:favorImageView];
    [favorImageView release];
    
    favorCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(227, 53, 28, 21)];
    
    
    [favorCountLabel setTextColor:Text_Color];
    
    
    favorCountLabel.text= [NSString stringWithFormat:@"%d",0];
    [favorCountLabel setFont:[UIFont systemFontOfSize:12]];
    favorCountLabel.backgroundColor=[UIColor clearColor];
    [self.scrollView addSubview:favorCountLabel];
    
    UIImageView *commentImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"said_top_iphone.png"]];
    
    [commentImageView setFrame:CGRectMake(259, 58, 14, 12)];
    
    [self.scrollView addSubview:commentImageView];
    [commentImageView release];
    
    
    
    commentCountLabel=[[UILabel alloc]initWithFrame:CGRectMake(274, 56, 28, 21)];
    
    
    [commentCountLabel setTextAlignment:UITextAlignmentRight];
    [commentCountLabel setTextColor:Text_Color];
    commentCountLabel.text= [NSString stringWithFormat:@"%d",0];
    [commentCountLabel setBackgroundColor:[UIColor clearColor]];
    [commentCountLabel setFont:[UIFont systemFontOfSize:12]];
    [commentCountLabel sizeToFit];
    commentCountLabel.backgroundColor=[UIColor clearColor];
    [self.scrollView addSubview:commentCountLabel];
    
    
    
    commentAndLikeImageView.userInteractionEnabled=YES;
    
    [commentAndLikeImageView release];
    
    [self.scrollView setContentSize:CGSizeMake(320, yuanJiaoView.frame.origin.y+yuanJiaoView.frame.size.height+60)];
        
}



- (void)conttentViewShadow
{
    yuanJiaoView.layer.cornerRadius = 2;
    
    yuanJiaoView.layer.shadowOpacity = 0.4;
	yuanJiaoView.layer.shadowRadius = 1.5;
	yuanJiaoView.layer.shadowOffset = CGSizeMake(0, 0);
    CGRect shadowFrame = yuanJiaoView.layer.bounds;
    CLog(@"shadow frame rect %f, %f, %f, %f", shadowFrame.origin.x, shadowFrame.origin.y, shadowFrame.size.width, shadowFrame.size.height);
    CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(shadowFrame.origin.x, shadowFrame.origin.y, shadowFrame.size.width, shadowFrame.size.height +2)].CGPath;
    yuanJiaoView.layer.shadowPath = shadowPath;
    
}


- (void)toPhotoBook:(NSArray *)images{
    
   
    BOOL isPersonalTimeline = NO;
    
    if ([self.type isEqualToString:@"timeline"]) {
        isPersonalTimeline = YES;
    }
       
    DiaryPhotoBrowseViewController *viewController = [[DiaryPhotoBrowseViewController alloc] initWithImages:pictureList  dateArray:nil page:0 localImageNum:0 isPersonalTimeline:isPersonalTimeline];

    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];
    
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [self.navigationController presentModalViewController:nav animated:YES];
    
    [viewController release];
    [nav release];

    
}


- (void)toLocalFullSize:(NSArray *)images{
    
    DiaryPhotoBrowseViewController *viewController = [[DiaryPhotoBrowseViewController alloc] initWithLocalImages:pictureList page:0];
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];
    
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    [self.navigationController presentModalViewController:nav animated:YES];
    
    [viewController release];
    [nav release];
    
    
}



#pragma mark - addcomment


-(void)setCommentPrama:(int)_superId commentTo:(int)_commentTo{
    
    self.superId = _superId;
    self.commentTo = _commentTo;
}


-(IBAction)commitComment:(NSString *)commentContent{
    
       
    self.commentText= commentContent;
    
    [self postComment];
    
    
  }

-(void)refreshComment{
    [self loadDetailDiaryWith:[NSString stringWithFormat:@"%d",[[self.diaryDict objectForKey:@"id"] intValue]] ];
    
}



-(void)postComment{
    //"id"(int)
    //"description"(String)
    //"createdDate"(long)
    //"modifiedBy"(int)
    //"title"(String)
    //"createdBy"(int,一个用户id，必须填写)
    //"publicDiary"(bool)
    
    
        if ([commentText isEqualToString:@""]) {
        
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"评论内容不能为空" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"取消" otherButtonTitles:nil];
                       
            [alert show];
            [alert release];

        return;
    }
    
    if (commentText.length > 140) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"评论内容不能超过140个字"
                                                       delegate:self
                                              cancelButtonTitle:@"取消" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        
        return;
    }

    
    
    [LoadingView showDefaultLoadingView];
          
    NSArray *keys = [NSArray arrayWithObjects:@"Author", @"Body", @"ThreadID",@"UserID", nil];
    
    NSString *_userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *_userId = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSArray *objects = [NSArray arrayWithObjects:_userName, self.commentText , [NSNumber numberWithInt:[[self.diaryDict objectForKey:@"ThreadID"] intValue]],_userId, nil];
        
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
   
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CreateMicroBlogComment.aspx",BASEURL,_userName];
	NSURL *url = [NSURL URLWithString:urlString];

    
    CLog(@"request %@", url);
       if (sendComment_connect != nil) {
        sendComment_connect.connectionDelegate = nil;
        [sendComment_connect release];
        sendComment_connect = nil;
    }
    
    sendComment_connect = [[ASIHTTPConnection alloc]initPOSTWithURL:url jsonData:jsonData resultDict:YES];
    sendComment_connect.connectionDelegate = self;
    [sendComment_connect startAsynchronous];
    [LoadingView showDefaultLoadingView];
    
    isAddNewComment = YES;
    
    
}


-(void)diaryLike:(id)sender{
    
 
    [LoadingView showDefaultLoadingView];
    
    NSString *diaryinfo=[NSString stringWithFormat:@"?uid=%d&did=%d",self.userId,[[self.diaryDict objectForKey:@"id"] intValue]];
    
    NSMutableURLRequest * request = [WebRequest diaryLikeRequestWith:diaryinfo];
    
    CLog(@"request %@", request);
    if (diaryLike_connection != nil) {
        diaryLike_connection.connectionDelegate = nil;
    }
    diaryLike_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];

    
}

#pragma mark -load data
#pragma mark  Load Data

- (void)loadDetailDiary{
    
    NSString *UserName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *threadId = [self.diaryDict objectForKey:@"ThreadID"];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/ShowMicroBlogThread.aspx?pageNo=%d&UserName=%@&ThreadID=%@",BASEURL,UserName,pageNo,UserName,threadId];
	NSURL *url = [NSURL URLWithString:urlString];
    
    if (getThread_connect != nil) {
        getThread_connect.connectionDelegate = nil;
        [getThread_connect release];
        getThread_connect = nil;
    }
    
    getThread_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    getThread_connect.connectionDelegate = self;
    
    [getThread_connect startAsynchronous];
    

}

#pragma mark ASIHTTPCONNECT delegate
- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
}

- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    CLog(@"detailThread = %@",dict);
    
    NSString *urlStr = [url absoluteString];
    NSRange rang = [urlStr rangeOfString:@"ShowMicroBlogThread"];
    if (rang.length > 0) {
        
        NSArray *array = [dict objectForKey:@"Records"];
        if (array.count > 0) {
            
            //commentView.hidden = NO;
            
            if(self.commentViewController == nil){
                commentViewController = [[CommentViewController alloc] initWithPost:array];
                commentViewController.delegate = self;
                //[commentView addSubview:commentViewController.view];
                [self.scrollView addSubview:commentViewController.view];
                
            }
            else{
                
                if (pageNo == 1) {
                    [self.commentViewController.commentArray removeAllObjects];
                    
                }
                              
                [self.commentViewController.commentArray addObjectsFromArray:array];
                [self.commentViewController.tableView reloadData];
                
              
            }
            
            if (commentViewController.tableView.contentSize.height <1000) {
                
                [commentViewController.view setFrame:CGRectMake(10, yuanJiaoView.frame.origin.y + yuanJiaoView.frame.size.height + 20, 280, 1000)];
                commentViewController.view.clipsToBounds = YES;
                
                [commentView setFrame:CGRectMake(commentView.frame.origin.x, commentView.frame.origin.y, commentView.frame.size.width, 100)];
                
                CLog(@"commentView x=%f y = %f height=%f",commentView.frame.origin.x,commentView.frame.origin.y,commentView.frame.size.height);
                
                [scrollView setContentSize:CGSizeMake(320,yuanJiaoView.frame.size.height+ MAX(1000, 100*array.count) +200  )];
            }
            else{
                [commentViewController.tableView reloadData];
                [commentViewController.view setFrame:CGRectMake(10, yuanJiaoView.frame.origin.y + yuanJiaoView.frame.size.height + 20, 280, 1000)];
                
                
                [scrollView setContentSize:CGSizeMake(320,yuanJiaoView.frame.size.height+1000  )];
                
            }
            


        }
        
    }
    
    
    rang = [urlStr rangeOfString:@"CreateMicroBlogComment"];
    if (rang.length > 0) {
        
        
        CLog(@"dict = %@",dict);
        
        if (dict) {
            if ([[dict objectForKey:@"isSuccess"] boolValue]) {
                
                pageNo = 1;
                [self loadDetailDiary];
                [LoadingView showDurationMessageLoadingViewWith:1 message:@"发布成功"];
                
            }
            else{
                
                [LoadingView showDurationMessageLoadingViewWith:2 message:[dict objectForKey:@"messageContent"]];
            }
        }
        
    }
    
}



- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    	
    
    //喜欢日志
	if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/diary/favor%@",BASEURL, [NSString stringWithFormat:@"?uid=%d&did=%@",self.userId,[self.diaryDict objectForKey:@"id"]]]]) {
        
        [self refreshComment];
        
    } 
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/diary/comment",BASEURL]]) {
        
        [self refreshComment];
        
    }
    
    
}

- (void)connectionArrayError:(NSError *)error{
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];


}





#pragma mark -WebConnection delegate

- (void)connectionSuccess:(NSDictionary *)dict{
    
}

- (void)connectionError:(NSError *)error{
    
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];
       
}
- (void)postSuccess:(NSString *)postinfo{
    CLog(@"post info");
    
    
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark -
#pragma mark UITextView delegate

-(void)textViewDidChange:(UITextView *)textView
{
	
	
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
	
    
    
	return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    textView.text = @"";
    textView.textColor = [UIColor blackColor];
	
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
	
	if ([textView.text isEqualToString:@""]) {
		textView.text = @"请输入您要评论的内容";
		textView.textColor = [UIColor lightGrayColor];
	}
	
	[textView resignFirstResponder];
	
}



#pragma mark comment view delegate
//comment view delegate

- (IBAction)toUserView:(id)sender{
    
    UIButton *button = (UIButton *)sender;

    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:backItem];
    
    PersonalViewController *viewControoer = [[PersonalViewController alloc]initWithUserId:button.tag];
    
    [self.navigationController pushViewController:viewControoer animated:YES];
    

    [viewControoer release];
}


-(void)toBabyTimelineView:(id)sender{
    
       
}



- (void)dealloc {
    
    
    CLog(@"TLDetailView dealloc");
    [commentViewController release];
    
    [containerView release];
    [textView release];
    
    //CLog(@"diaryComment_connection retainCount %d",   diaryComment_connection.retainCount );
    
    if (getThread_connect != nil) {
        
        getThread_connect.connectionDelegate = nil;
        [getThread_connect release];
        getThread_connect = nil;
        
    }
    if (sendComment_connect != nil) {
        sendComment_connect.connectionDelegate = nil;
        [sendComment_connect release];
        sendComment_connect = nil;
    }
    
    
    if (diaryComment_connection != nil) {
          diaryComment_connection.connectionDelegate = nil;
        [diaryComment_connection release];
        diaryComment_connection = nil;
    }
    
    
    
    if (diaryLike_connection != nil) {
         diaryLike_connection.connectionDelegate = nil;
        [diaryLike_connection release];
        diaryLike_connection = nil;
    }
    if (diaryContent_connection != nil) {
         diaryContent_connection.connectionDelegate = nil;
        [diaryContent_connection release];
        diaryContent_connection = nil;
    }
      
    
    
    [type release];
    
    [favorCountLabel release];
	[diaryDict release];
	[userIcon release];
	[userName release];
	
	[localLabel release];
    [scrollView release];
    [commentView release];
    
    //add comment
    
    [commentText release];
   
    [commentCountLabel release];
    
    [backGoundButton release];
    
    [super dealloc];
}


#pragma mark--
#pragma  mark GroingTextView methord

- (void)initGrowingTextView{
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.contentView.frame.size.height -50, 320, 50)];
    //
    containerView.backgroundColor = [UIColor redColor];
    
    
	textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(40, 10, 213, 50)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	textView.minNumberOfLines = 1;
	textView.maxNumberOfLines = 6;
	textView.returnKeyType = UIReturnKeyGo; //just as an example
	textView.font = [UIFont systemFontOfSize:15.0f];
	textView.delegate = self;
    //textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 5, 0);
    
    textView.backgroundColor = [UIColor whiteColor];
    
    // textView.text = @"test\n\ntest";
	// textView.animateHeightChange = NO; //turns off animation
    
    // [self.delegate addGrowingTextView:containerView];
    [self.contentView insertSubview:containerView aboveSubview:backGoundButton];
	
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    //entryImageView.frame = CGRectMake(5, 0, 248, 40);
    
    entryImageView.frame = CGRectMake(40, 0, 213, 50);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    //发送评论
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	doneBtn.frame = CGRectMake(containerView.frame.size.width - 69, 12, 63, 27);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[doneBtn setTitle:@"评论" forState:UIControlStateNormal];
    
    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
	[containerView addSubview:doneBtn];
    
    
    //喜欢
    
    //    UIImage *likeBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    //    UIImage *selectedLikeBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	likeBtn.frame = CGRectMake(5, 15, 26, 20);
    likeBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	//[likeBtn setTitle:@"喜欢" forState:UIControlStateNormal];
    
    //    [likeBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    //    likeBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    //    likeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [likeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[likeBtn addTarget:self action:@selector(diaryLike:) forControlEvents:UIControlEventTouchUpInside];
    //    [likeBtn setBackgroundImage:likeBtnBackground forState:UIControlStateNormal];
    //    [likeBtn setBackgroundImage:selectedLikeBtnBackground forState:UIControlStateSelected];
    
    
    [likeBtn setImage:[UIImage imageNamed:@"like_down_iphone.png"] forState:UIControlStateNormal];
	[containerView addSubview:likeBtn];
    
    
    
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    
}

-(void)resignTextView
{
    [self commitComment:textView.text ];
    textView.text = @"";
    
	[textView resignFirstResponder];
}


- (IBAction)backGroundTap{
    
    [textView resignFirstResponder];
    textView.text = @"";
    
}


//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    // containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    
    
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - (keyboardBounds.size.height + containerFrame.size.height);
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    backGoundButton.hidden = NO;
    
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - containerFrame.size.height;
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	containerView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    backGoundButton.hidden = YES;
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}



@end
